#-------------------------------------------------------------------------------
# By Daoyu @2010-07-08
#-------------------------------------------------------------------------------
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.template import RequestContext

from uncle.users.models import *
from uncle.util.page import *
from uncle.project.models import *

from django.core.mail import *

def get_all_cat_skill_tool_tag(user):
    skts = []
    for x in Category.objects.all():
        skt = skill_tool_tag(x)
        #[skt.add_tag(y) for y in Tag_user.objects.filter(tag__category = x).filter(user__id=user)]
        [skt.add_skill(y) for y in Skill_user.objects.filter(skill__category = x).filter(user__id = user)]
        [skt.add_tool(y) for y in Tool_user.objects.filter(tool__category = x).filter(user__id = user)]

        if skt.skills or skt.tools:
            skts.append(skt)
    return skts

#-------------------------------------------------------------------------------
# Change the customerized skills
#-------------------------------------------------------------------------------
@login_required
def change_customer_skills(request, u_id):
    if not request.user.has_perm('users.is_producer'):
        return HttpResponseRedirect('/403/?msg=You do not have permission to view this page')
    if request.method == 'POST':
        up = User_profile.objects.get(user__id = u_id)
        up.customer_skills = request.POST['customer_skills']
        up.save()
        request.user.message_set.create(message = 'Successfully change the note')
        return HttpResponseRedirect(request.GET['url'])
    
#-------------------------------------------------------------------------------
# Change the customerized skills
#-------------------------------------------------------------------------------
@login_required
def change_client_text(request, u_id):
    if not request.user.has_perm('users.is_producer'):
        return HttpResponseRedirect('/403/?msg=You do not have permission to view this page')
    if request.method == 'POST':
        up = User_profile.objects.get(user__id = u_id)
        up.client_text = request.POST['client_text']
        up.save()
        request.user.message_set.create(message = 'Successfully changed the client text')
        return HttpResponseRedirect(request.GET['url'])

#-------------------------------------------------------------------------------
# Change given user's note.
#-------------------------------------------------------------------------------
@login_required
def change_note(request, u_id):
    if not request.user.has_perm('users.is_producer'):
        return HttpResponseRedirect('/403/?msg=You do not have permission to view this page')
    if request.method == 'POST':
        up = User_profile.objects.get(user__id = u_id)
        up.note = request.POST['note']
        up.save()
        request.user.message_set.create(message = 'Successfully change the note')
        return HttpResponseRedirect(request.GET['url'])

#-------------------------------------------------------------------------------
# Show the detail of an artist. u_id means user id.
# When the page is viewed, the artist has a visit + 1;
#-------------------------------------------------------------------------------
@login_required
def show_detail(request, u_id):
    user = User.objects.filter(id = u_id)
    if not user: # If wrong u_id.
        return HttpResponseRedirect('/403/?msg=The user does not exist')

    if user[0].has_perm('users.is_artist'): # visits ++
        es = Email_sta.objects.filter(user__id = u_id)
        if es:
            es[0].visits = es[0].visits + 1
            es[0].save()

    _u_e, u_e = User_expire.objects.filter(user__id = u_id), User_expire()
    if _u_e:
        u_e = _u_e[0]
    else:
        u_e.user = user[0]
        u_e.save()

    movies = video.objects.filter(user__id = u_id)
    _movies = split_into_pages(request, movies, 4)
    attachs = User_attachment.objects.all()

    skts = get_all_cat_skill_tool_tag(u_id)

    return render_to_response('user/detail.html',
              {'user_detail':user[0], 'movies':_movies,
               'skts':skts, 'user_exp':u_e, 'attachs':attachs,},
              context_instance = RequestContext(request))    
    
#-------------------------------------------------------------------------------
# Handle the request for upload a new video. u_id is for whom to upload.
#-------------------------------------------------------------------------------
@login_required
def send_upload_request(request, u_id):
    if request.method == 'POST':
        ur = Upload_request()
        _user = User.objects.filter(id = u_id)
        ur.user = _user[0]
        if request.user.id: # if a logged in user request.
            ur.text = request.user.first_name + ' ' \
                + request.user.last_name + ': ' + request.POST['upload_request']
        else: # if a anonymous user
            ur.text = request.POST['upload_request']

        ur.save()

        _html = """Dear %s, <p>You have got a new upload request from UNCLE.</p>
        <p>%s</p>
        <p> Please click the following link to upload! Your username is "%s"</p>
        <p><a href="http://216.180.238.64/user/upload/?ur=%s">http://216.180.238.64/user/upload/?ur=%s</a></p>
        Best regards,<br>
        From UNCLE        
        """

        email = EmailMultiAlternatives('New upload request from UNCLE',
                                        _html % (_user[0].first_name + ' ' + _user[0].last_name,
                                                 ur.text, _user[0].username, str(ur.id), str(ur.id)
                                               ) ,
                                        bcc = ['noreply@uncle-berlin.de'],
                                        to = [_user[0].email])
        email.content_subtype = "html"
        
        try:
            email.send()
            request.user.message_set.create(message='E-mail request successfully sent!!')
        except:
            request.user.message_set.create(message='Send email encounted problem')        

        return HttpResponseRedirect ('/user/' + str(u_id) + '/')

#-------------------------------------------------------------------------------
# View all the upload requests.  
#-------------------------------------------------------------------------------
@login_required
def get_upload_request(request):
    if request.method == 'GET':
        urs = Upload_request.objects.filter(user__id = request.user.id)

        return render_to_response('user/upload_request.html',
              {'requests':urs, },
              context_instance = RequestContext(request))

@login_required
def delete_upload_request(request, u_id):
    if request.method == 'GET':
        urs = Upload_request.objects.filter(id = u_id)
        if urs and urs[0].user.id == request.user.id:
            urs[0].delete()

            request.user.message_set.create(
                message = 'Delete an upload request.')
        return HttpResponseRedirect('/user/requests/')

#-------------------------------------------------------------------------------
# Play the given video with id = v_id
#-------------------------------------------------------------------------------
def play(request, v_id):
    if request.method == 'GET':
        _video = video.objects.filter(id = v_id)
        if not _video:
            return HttpResponseRedirect('/403/?msg=The video you view does not exist')

        bas = None
        if request.user.has_perm('users.is_producer'):
            bas = Basket.objects.filter(user__id = request.user.id)

        return render_to_response('user/play_video.html',
            {'video':_video[0], 'bas':bas, },
            context_instance = RequestContext(request))

#-------------------------------------------------------------------------------
# User Upload a attachment to the system.
#-------------------------------------------------------------------------------
@login_required
def upload_attachment(request):
    if request.method == 'GET':
        return render_to_response('user/upload_attachment.html',
            {},
            context_instance = RequestContext(request))
    elif request.method == 'POST':
        attach = User_attachment()
        attach.text = request.POST['desc']
        attach.title = request.POST['title']
        attach.user = request.user

        if(request.FILES.has_key('file')):
            from uncle.util.file import upload
            _f_name = upload('upload/video/' + str(request.user.id),
                             request.FILES['file'] ,
                             pre = '/var/www/uncle/')            
            
            attach.file = _f_name           

        attach.save()

        request.user.message_set.create(
            message = 'New attachment uploaded')
       
        return HttpResponseRedirect('/user/' + str(request.user.id) + '/')        

#-------------------------------------------------------------------------------
# User Upload a video to the system.
#-------------------------------------------------------------------------------
@login_required
def upload_video(request):
    if request.method == 'GET':
        if request.GET.has_key('ur'):
            ur = Upload_request.objects.filter(id = request.GET['ur'])
            if ur:
                return render_to_response('user/upload_video.html',
                    {'up_req':ur[0], },
                    context_instance = RequestContext(request))
        return render_to_response('user/upload_video.html',
            {},
            context_instance = RequestContext(request))
    elif request.method == 'POST':
        _video = video()
        _video.text = request.POST['desc']
        _video.title = request.POST['title']
        _video.user = request.user

        if(request.FILES.has_key('video')):
            from uncle.util.file import upload
            _f_name = upload('upload/video/' + str(request.user.id),
                             request.FILES['video'] ,
                             pre = '/var/www/uncle/',
                             type = '.mp4')

            f_name = _f_name.split('.')[0]

            import os
            os.system('/usr/local/bin/ffmpeg -i /var/www/uncle/' + _f_name
                      + ' -vcodec libx264 -vpre slow -vpre ipod640 -s 480x360 /var/www/uncle/'
                      + f_name + '.mp4')

            os.system('/usr/local/bin/ffmpeg -i /var/www/uncle/' + _f_name +
                    ' /var/www/uncle/' + f_name + '.jpg')

            os.system('rm /var/www/uncle/' + _f_name)

            _video.movie = f_name + '.mp4'
            up = User_profile.objects.get(user__id = request.user.id)
            up.film = _video.movie
            up.save()

        _video.save()

        if request.POST['u_req']: # if successful upload, remove the upload request.
            _id = request.POST['u_req']
            Upload_request.objects.filter(id = _id).delete()

        request.user.message_set.create(
            message = 'New video uploaded')
       # return HttpResponseRedirect('/video/' + str(_video.id) + '/')
        return HttpResponseRedirect('/user/upload/')
        # ('/user/upload/?ur=%s' + '/') 
